package com.face.pass.active.utils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OkHttpUtils {
	public static final MediaType type = MediaType.parse("application/json;charset=utf-8");
	public static OkHttpClient httpClient = new OkHttpClient();
	
	static {
		httpClient = httpClient.newBuilder()
				.connectTimeout(2, TimeUnit.SECONDS)
				.writeTimeout(5, TimeUnit.SECONDS)
				.readTimeout(5, TimeUnit.SECONDS)
				.build();
	}

	// Get方法调用服务
	public static String httpGet(HttpUrl url) throws IOException {
		Request request = new Request.Builder().url(url).build();
		Response response = httpClient.newCall(request).execute();
		return response.body().string();// 返回的是string 类型
	}

	// Post方法调用服务
	public static String httpPost(HttpUrl url, String content) throws IOException {
		RequestBody requestBody = RequestBody.create(type, content);
		Request request = new Request.Builder().url(url).post(requestBody).build();
		Response response = httpClient.newCall(request).execute();
		return response.body().string();
	}
}
